import { asyncRoutes, constantRoutes } from '@/router'
import _ from 'lodash'
import addDataRoute from '@/router/modules/addroute'

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  // if(['dataManagement', 'permissionManagement', 'settingsManagement'].indexOf(route.name) !== -1){
  //   return 1
  // }
  if (!route.needAuth) {
    return {
      index: 1
    }
  }else {
    let index = _.findIndex(roles, { 'menuUrl': route.name })
    let item = _.find(roles, { 'menuUrl': route.name })
    return {
      index,
      item
    }
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRoutes
 * @param roles
 */
function filterAsyncRoutes(routes, roles, newroutes) {
  const res = []
  routes.forEach((route) => {
    const tmp = { ...route }
    const hasPer = hasPermission(roles, tmp)
    if (hasPer.index !== -1) {
      tmp.meta.menuId = hasPer.item ? hasPer.item.id : '' // 设置菜单id
      tmp.meta.rights = hasPer.item ? hasPer.item.rights : '' // 设置功能权限
      if (tmp.children) {
        if (tmp.name==='dataManagement' && newroutes){
          const newroute= addDataRoute(newroutes, roles)
          tmp.children=tmp.children.concat(newroute)
        }else{
          tmp.children = filterAsyncRoutes(tmp.children, roles)
        }
        if(tmp.children.length){
          tmp.children[0].meta.menuId = hasPer.item ? hasPer.item.id : '' // 设置菜单id
          tmp.children[0].meta.rights = hasPer.item ? hasPer.item.rights : '' // 设置功能权限
        }
      }
      if (tmp.name === 'dataManagement' && tmp.children.length) {
        res.push(tmp)
      } 
      if (tmp.name !=='dataManagement') {
        res.push(tmp)
      }
    }
  })
  return res
}

/**
 * 动态添加子路由
 * @param routes asyncRoutes
 * @param roles
 */
 function addAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach((route) => {
    const tmp = { ...route }
    if (tmp.name==='dataManagement'){
      const newroute= addDataRoute(roles)
      tmp.children=tmp.children.concat(newroute)
    }
    res.push(tmp)
  })
  return res
}

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    // hasWarnManagePermission: 0,
    // backendManageWhiteList: ['admin']
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    CLEAR_ROUTES: (state) => {
      state.addRoutes = []
      state.routes = []
    }
  },
  actions: {
    generateRoutes({ commit }, data) {
      let roles= data.roles
      let newroutes= data.newroutes
      return new Promise(resolve => {
        const newasyncRoutes = Number(localStorage.projectId) === 2 ? asyncRoutes.fuzhou : asyncRoutes.heze
        let accessedRoutes = filterAsyncRoutes(newasyncRoutes, roles, newroutes)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    },
    clearRoutes({ commit}) {
      return new Promise(resolve => {
        commit('CLEAR_ROUTES')
        resolve()
      })
    },
    addRoutes({ commit}, data) {
      let roles= data.roles
      let newroutes= data.newroutes
      return new Promise(resolve => {
        const newasyncRoutes = Number(localStorage.projectId) === 2 ? asyncRoutes.fuzhou : asyncRoutes.heze
        let addRoutes = addAsyncRoutes(newasyncRoutes, roles, newroutes)
        commit('SET_ROUTES', addRoutes)
        resolve(addRoutes)
      })
    }
  }
}

export default permission
